"""
监控任务数据模型
"""

from sqlalchemy import Column, Integer, String, DateTime, Boolean, ForeignKey, Text, Enum
from sqlalchemy.dialects.mysql import JSON
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship
import enum

from app.database import Base


class MonitorType(enum.Enum):
    """监控类型枚举"""
    KEYWORD = "keyword"    # 关键词监控
    SELLER = "seller"      # 卖家监控
    SHOP = "shop"          # 店铺监控


class MonitorStatus(enum.Enum):
    """监控状态枚举"""
    PENDING = "pending"      # 待启动
    ACTIVE = "active"        # 运行中
    EXPIRED = "expired"      # 已过期
    STOPPED = "stopped"      # 已停止
    ERROR = "error"          # 错误状态


class Monitor(Base):
    """监控任务表"""
    __tablename__ = "monitors"

    # 基础字段
    id = Column(Integer, primary_key=True, index=True, comment="监控任务ID")
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False, comment="用户ID")
    
    # 监控配置
    monitor_type = Column(Enum(MonitorType), nullable=False, comment="监控类型")
    name = Column(String(200), nullable=False, comment="监控任务名称")
    description = Column(Text, nullable=True, comment="监控描述")
    
    # 监控条件（JSON格式存储）
    conditions = Column(JSON, nullable=False, comment="监控条件")
    # 示例：
    # 关键词监控: {"keyword": "煤炉", "include_description": true}
    # 卖家监控: {"seller_id": "12345", "seller_name": "某某店铺"}
    # 店铺监控: {"product_id": "NT45FPfxhfXbHtzPXcE7ne", "shop_name": "ゴリランShop"}
    
    # 监控状态
    status = Column(Enum(MonitorStatus), default=MonitorStatus.PENDING, comment="监控状态")
    is_active = Column(Boolean, default=True, comment="是否激活")
    
    # 时间配置
    duration_hours = Column(Integer, default=24, comment="监控时长（小时）")
    check_interval = Column(Integer, default=15, comment="检查间隔（秒）：15,10,5,3")
    started_at = Column(DateTime(timezone=True), nullable=True, comment="开始时间")
    expires_at = Column(DateTime(timezone=True), nullable=True, comment="过期时间")
    
    # 监控统计
    total_found = Column(Integer, default=0, comment="发现商品总数")
    total_notified = Column(Integer, default=0, comment="通知发送总数")
    last_check_at = Column(DateTime(timezone=True), nullable=True, comment="最后检查时间")
    
    # 错误信息
    error_message = Column(Text, nullable=True, comment="错误信息")
    error_count = Column(Integer, default=0, comment="错误次数")
    
    # 时间字段
    created_at = Column(DateTime(timezone=True), server_default=func.now(), comment="创建时间")
    updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), comment="更新时间")
    
    # 关联关系
    user = relationship("User", back_populates="monitors")
    product_notifications = relationship("ProductNotification", back_populates="monitor", cascade="all, delete-orphan")
    notifications = relationship("Notification", back_populates="monitor", cascade="all, delete-orphan")
    notify_logs = relationship("NotifyLog", back_populates="monitor", cascade="all, delete-orphan")

    def __repr__(self):
        return f"<Monitor(id={self.id}, user_id={self.user_id}, type={self.monitor_type.value}, name='{self.name}')>"

    @property
    def is_expired(self):
        """检查是否已过期"""
        if not self.expires_at:
            return False
        return func.now() > self.expires_at

    @property
    def remaining_hours(self):
        """剩余监控时间（小时）"""
        if not self.expires_at:
            return 0
        remaining = self.expires_at - func.now()
        return max(0, remaining.total_seconds() / 3600)

    def get_keyword(self):
        """获取关键词（仅关键词监控）"""
        if self.monitor_type == MonitorType.KEYWORD:
            return self.conditions.get("keyword", "")
        return None

    def get_seller_info(self):
        """获取卖家信息（仅卖家监控）"""
        if self.monitor_type == MonitorType.SELLER:
            return {
                "seller_id": self.conditions.get("seller_id", ""),
                "seller_name": self.conditions.get("seller_name", "")
            }
        return None

    def get_shop_info(self):
        """获取店铺信息（仅店铺监控）"""
        if self.monitor_type == MonitorType.SHOP:
            return {
                "product_id": self.conditions.get("product_id", ""),
                "shop_name": self.conditions.get("shop_name", "")
            }
        return None

    @classmethod
    def create_keyword_monitor(cls, user_id, keyword, name=None, duration_hours=24):
        """创建关键词监控"""
        return cls(
            user_id=user_id,
            monitor_type=MonitorType.KEYWORD,
            name=name or f"关键词监控: {keyword}",
            conditions={"keyword": keyword, "include_description": True},
            duration_hours=duration_hours
        )

    @classmethod
    def create_seller_monitor(cls, user_id, seller_id, seller_name, name=None, duration_hours=24):
        """创建卖家监控"""
        return cls(
            user_id=user_id,
            monitor_type=MonitorType.SELLER,
            name=name or f"卖家监控: {seller_name}",
            conditions={"seller_id": seller_id, "seller_name": seller_name},
            duration_hours=duration_hours
        )

    @classmethod
    def create_shop_monitor(cls, user_id, product_id, shop_name, name=None, duration_hours=24):
        """创建店铺监控"""
        return cls(
            user_id=user_id,
            monitor_type=MonitorType.SHOP,
            name=name or f"店铺监控: {shop_name}",
            conditions={"product_id": product_id, "shop_name": shop_name},
            duration_hours=duration_hours
        )
